﻿using System;
using System.Collections.Generic;
using System.Text;
using Ultimus.WFServer;
using MyLib.Data;

namespace Task.Logic
{
    public class FieldLogic
    {
        Dictionary<string, List<string>> _dict = new Dictionary<string, List<string>>();
        public List<string> GetFieldList(string dataSourceDB,string fieldListName)
        {
            List<string> strs=new List<string>();
            if(!_dict.TryGetValue(fieldListName, out strs))
            {
                strs = new List<string>();
                Variable[] vars = GetMainSS(dataSourceDB,fieldListName);
                for (int i = 0; i < vars.Length; i++)
                {
                    strs.Add(vars[i].strVariableName);
                }
                _dict.Add(fieldListName, strs);
            }
            return strs;
        }

        Variable[] GetMainSS(string dataSourceDB, string processName)
        {
            Variable[] vars = null;
            string obj = DataAccess.Instance(dataSourceDB).ExecuteScalar<string>("select top 1 INITIATEID from INITIATE where  ProcessName='" + processName + "' order by PROCESSVERSION desc");
            if (!string.IsNullOrEmpty(obj))
            {
                string taskID = obj.ToString();
                if (!string.IsNullOrEmpty(taskID))
                {
                    Ultimus.WFServer.Task t = new Ultimus.WFServer.Task();
                    t.InitializeFromInitiateTaskId("", taskID);
                    string error = "";
                    t.GetAllTaskVariables(out vars, out error);
                }
            }
            return vars;
        }

        public void ClearFieldList(string fieldListName)
        {
           if (_dict.ContainsKey(fieldListName))
           {
               _dict.Remove(fieldListName);
           }
        }
    }
}
